//
//  MTRedpacketDateCellRow.swift
//  MT
//
//  Created by ooops on 2020/5/15.
//  Copyright © 2020 张强. All rights reserved.
//

import Foundation
import Eureka
import MTCategory

public final class MTRedpacketDate: MTRedpacketDateRow, RowType {
    required public init(tag: String?) {
        super.init(tag: tag)
    }
}

open class MTRedpacketDateRow: MTRedpacketDateCellRow {
    required public init(tag: String?) {
        super.init(tag: tag)
        dateFormatter = DateFormatter()
        dateFormatter?.timeStyle = .none
        dateFormatter?.dateStyle = .medium
        dateFormatter?.locale = Locale.current
    }
}

public protocol MTRedpacketDateCellProtocol: class {
    var minimumDate: Date? { get set }
    var maximumDate: Date? { get set }
    var minuteInterval: Int? { get set }
}

open class MTRedpacketDateCell: Cell<Date>, CellType {

    public var datePicker: UIDatePicker

    public required init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        datePicker = UIDatePicker()
        datePicker.locale = Locale(identifier: "zh_CN")
        datePicker.datePickerMode = .time
        super.init(style: style, reuseIdentifier: reuseIdentifier)
    }

    required public init?(coder aDecoder: NSCoder) {
        datePicker = UIDatePicker()
        datePicker.locale = Locale(identifier: "zh_CN")
        datePicker.datePickerMode = .time
        super.init(coder: aDecoder)
    }

    var tipText: String? {
        didSet {
            self.tipLabel.text = tipText
        }
    }
    
    func setupAccessoryView(text: String?, image: String?) {
        if text != nil {
            self.customAccessorTextyView.text = text
            customAccessoryView.isHidden = true
            customAccessorTextyView.isHidden = false
            return
        }
        if image != nil {
            customAccessorTextyView.isHidden = true
            customAccessoryView.isHidden = false
            customAccessoryView.image = UIImage(named: image!)
            return
        }
    }
    
    var placeholder: String? {
        didSet {
            if let p = placeholder {
                contentTextLabel.attributedText = NSAttributedString(string: p, attributes: [NSAttributedString.Key.foregroundColor : UIColor.text.x9b9b9b, NSAttributedString.Key.font : PingFangSCMediumFont(14)])
            }
        }
    }
    
    lazy var bgView: UIView = {
        let v = UIView()
        v.backgroundColor = .white
        v.layer.cornerRadius = 8
        return v
    }()
    
    /// 显示模式
    lazy var tipLabel: UILabel = {
        let l = UILabel()
        l.font = PingFangSCSemiboldFont(14)
        l.textColor = UIColor.text.x1d1a1a
        l.text = "名称"
        l.textAlignment = .left
        l.setContentHuggingPriority(.defaultHigh, for: .horizontal)
        return l
    }()
    
    lazy var customAccessoryView: UIImageView = {
            let imageV = UIImageView(image: UIImage(named: "icon_right_gary"))
            return imageV
    }()
    
    lazy var customAccessorTextyView: UILabel = {
        let l = UILabel()
        l.font = PingFangSCSemiboldFont(14)
        l.textColor = UIColor.text.x1d1a1a
        return l
    }()
    
    lazy var contentTextLabel: UILabel = {
        let txf = UILabel()
        txf.textColor = UIColor.text.x9b9b9b
        txf.font = PingFangSCMediumFont(14)
        txf.textAlignment = .right
        return txf
    }()
    
    open override func setup() {
        super.setup()
        backgroundColor = UIColor(hex: 0xf4f4f4)
        selectionStyle = .none
        textLabel?.isHidden = true
        detailTextLabel?.isHidden = true
        editingAccessoryType =  .none
        
        contentView.addSubview(bgView)
        bgView.addSubview(tipLabel)
        bgView.addSubview(contentTextLabel)
        bgView.addSubview(customAccessoryView)
        bgView.addSubview(customAccessorTextyView)
        datePicker.addTarget(self, action: #selector(MTClubDetailDateCell.datePickerValueChanged(_:)), for: .valueChanged)
        makeConstraint()
    }
    
    private func makeConstraint() {
        bgView.snp.makeConstraints { (make) in
            make.top.bottom.equalToSuperview()
            make.left.equalToSuperview().offset(8)
            make.right.equalToSuperview().offset(-8)
        }
        
        tipLabel.snp.makeConstraints { (make) in
            make.centerY.equalToSuperview()
            make.left.equalToSuperview().offset(10)
            make.width.greaterThanOrEqualTo(30)
        }
        
        contentTextLabel.snp.makeConstraints { (make) in
            make.centerY.equalToSuperview()
            make.left.equalTo(tipLabel.snp.right)
            make.right.equalTo(customAccessoryView.snp.left).offset(-9)
        }

        customAccessoryView.snp.makeConstraints { (make) in
            make.right.equalToSuperview().offset(-8)
            make.centerY.equalTo(tipLabel)
            make.width.height.equalTo(15)
        }
        
        customAccessorTextyView.snp.makeConstraints { (make) in
            make.right.equalToSuperview().offset(-8)
            make.centerY.equalTo(tipLabel)
            make.width.height.equalTo(15)
        }
    }

    deinit {
        datePicker.removeTarget(self, action: nil, for: .allEvents)
    }

    open override func update() {
        super.update()
        if row.value != nil {
            //contentTextLabel.text = row.displayValueFor?(row.value)
            if let v = row.value {
                contentTextLabel.text = DateManager.string(date: v, format: "HH:mm")
            }
        } else {
            datePicker.setDate(row.value ?? Date(), animated: row is CountDownPickerRow)
            datePicker.minimumDate = (row as? MTClubDetailDateCellProtocol)?.minimumDate
            datePicker.maximumDate = (row as? MTClubDetailDateCellProtocol)?.maximumDate
            if let minuteIntervalValue = (row as? MTClubDetailDateCellProtocol)?.minuteInterval {
                datePicker.minuteInterval = minuteIntervalValue
            }
        }
    }

    open override func didSelect() {
        super.didSelect()
        row.deselect()
    }

    override open var inputView: UIView? {
        if let v = row.value {
            datePicker.setDate(v, animated:row is CountDownRow)
        }
        return datePicker
    }

    @objc func datePickerValueChanged(_ sender: UIDatePicker) {
        row.value = sender.date
        if let v = row.value {
            contentTextLabel.text = DateManager.string(date: v, format: "HH:mm")
        }
    }

    private func datePickerMode() -> UIDatePicker.Mode {
        switch row {
        case is DateRow:
            return .date
        case is TimeRow:
            return .time
        case is DateTimeRow:
            return .dateAndTime
        case is CountDownRow:
            return .countDownTimer
        default:
            return .date
        }
    }

    open override func cellCanBecomeFirstResponder() -> Bool {
        return canBecomeFirstResponder
    }

    override open var canBecomeFirstResponder: Bool {
        return !row.isDisabled
    }
    
    open override func resignFirstResponder() -> Bool {
        if let date = self.row.value {
            datePicker.setDate(date, animated: true)
            return super.resignFirstResponder()
        }
        let date = Date()
        datePicker.setDate(row.value ?? date, animated: row is CountDownPickerRow)
        datePicker.minimumDate = (row as? MTCreatePartyDateCellProtocol)?.minimumDate
        datePicker.maximumDate = (row as? MTCreatePartyDateCellProtocol)?.maximumDate
        if let minuteIntervalValue = (row as? MTCreatePartyDateCellProtocol)?.minuteInterval {
            datePicker.minuteInterval = minuteIntervalValue
        }
        
        row.value = date
        contentTextLabel.text = DateManager.string(date: date, format: "yyyy/MM/dd HH:mm")
        
        return super.resignFirstResponder()
    }
}

open class MTRedpacketDateCellRow: Row<MTRedpacketDateCell>, MTRedpacketDateCellProtocol, NoValueDisplayTextConformance {

    /// The minimum value for this row's UIDatePicker
    open var minimumDate: Date?

    /// The maximum value for this row's UIDatePicker
    open var maximumDate: Date?

    /// The interval between options for this row's UIDatePicker
    open var minuteInterval: Int?

    /// The formatter for the date picked by the user
    open var dateFormatter: DateFormatter?

    open var noValueDisplayText: String? = nil

    required public init(tag: String?) {
        super.init(tag: tag)
        displayValueFor = { [unowned self] value in
            guard let val = value, let formatter = self.dateFormatter else { return nil }
            return formatter.string(from: val)
        }
    }
}

